package com.fly.docker.service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.stereotype.Service;

import com.spotify.docker.client.DefaultDockerClient;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.messages.Container;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class DockerService
{
    List<DockerClient> dockerClients = new CopyOnWriteArrayList<>();
    
    @PostConstruct
    public void init()
    {
        if (SystemUtils.IS_OS_UNIX)
        {
            log.info("######## docker init by Unix socket");
            dockerClients.add(new DefaultDockerClient("unix:///var/run/docker.sock"));
        }
    }
    
    /**
     * 新增docker客户端
     * 
     * @param dockerclient
     * @see [类、类#方法、类#成员]
     */
    public void add(DockerClient dockerclient)
    {
        dockerClients.add(dockerclient);
    }
    
    /**
     * 返回活跃节点
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    public List<DockerClient> getClients()
    {
        return dockerClients;
    }
    
    /**
     * 返回远程docker host
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    public List<String> getRemoteDockers()
    {
        return dockerClients.stream().map(d -> d.getHost()).filter(host -> !StringUtils.contains(host, "localhost")).collect(Collectors.toList());
    }
    
    /**
     * 选择本地DockerClient
     * 
     * @return
     * @throws DockerException
     * @see [类、类#方法、类#成员]
     */
    public DockerClient chooseLocal()
        throws DockerException
    {
        return choose("localhost");
    }
    
    /**
     * 选择远程DockerClient
     * 
     * @return
     * @throws DockerException
     * @see [类、类#方法、类#成员]
     */
    public DockerClient choose(String dockerHost)
        throws DockerException
    {
        if (dockerClients.isEmpty())
        {
            throw new DockerException("未检测到活跃DockerClient，请先初始化");
        }
        return dockerClients.stream().filter(d -> StringUtils.equals(d.getHost(), dockerHost)).findFirst().get();
    }
    
    /**
     * 获取运行容器信息
     * 
     * @return
     * @throws InterruptedException
     * @throws DockerException
     * @see [类、类#方法、类#成员]
     */
    public List<Container> getContainers()
        throws DockerException, InterruptedException
    {
        List<DockerClient> clients = getClients();
        if (clients.isEmpty())
        {
            return Collections.emptyList();
        }
        DockerClient dockerClient = clients.get(0);
        return dockerClient.listContainers();
    }
}
